package org.streets.eis.ext.analysis.components;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.PropertyModel;
import org.streets.database.Limits;
import org.streets.database.RecordHandler;
import org.streets.database.SQLConnection;
import org.streets.eis.util.Pager;

public class SelectPage extends WebPage
{
	@Inject
	private SQLConnection connection;
	
	private List<CheckItem> items=new ArrayList<CheckItem>();
	
	private CheckItem checkedItem;
	private Pager pager = new Pager(0);
	private String tableName;
	
	WebMarkupContainer refreshArea = new WebMarkupContainer("refreshArea");
	
	@SuppressWarnings("unchecked")
	public SelectPage(final ProcessSelectedValue processor, final ModalWindow window){

		Form form = new Form("form");
		add(form);
		
		items.add(new CheckItem("1","v1"));//不能给空?
		
		refreshArea.add(new AjaxLink("closeOK"){
				private static final long serialVersionUID = 1L;

				@Override
				public void onClick(AjaxRequestTarget target)
				{
					//返回值的两种方式：
					//1.给定了处理接口，调用接口处理;
					//2.没有给定处理接口，则使用checkedItem属性在外部处理;
					//【由于刷新的问题，现在只能使用第2种方式】
					checkedItem = getCheckedItem(items);//选定值
					if (checkedItem != null){
						if (processor != null){
							processor.processSelectedValue(checkedItem);
						}
						window.close(target);
					}else{
					}
				}
			});

		refreshArea.add(new AjaxLink("closeCancel")
			{
				private static final long serialVersionUID = 1L;

				@Override
				public void onClick(AjaxRequestTarget target)
				{
					window.close(target);
				}
			});
		
		add(refreshArea);		
		ListView<CheckItem> lv = new ListView<CheckItem>("list", items) {
				private static final long serialVersionUID = 1L;
				@Override
				protected void populateItem(ListItem<CheckItem> item) {
						final CheckItem ci = (CheckItem) item.getModelObject();
						AjaxCheckBox checkbox = new AjaxCheckBox("chkBox",new PropertyModel<Boolean>(ci,"checked")){
							private static final long serialVersionUID = 1L;
							@Override
							protected void onUpdate(AjaxRequestTarget target) {
								if(ci.getChecked()){
									for(CheckItem item : items){
										if (!(ci.getId().equalsIgnoreCase(item.getId()))){
										  item.setChecked(false);
										}
									}
								}
							}
						};
						item.add(checkbox);
						item.add(new Label("lblId", ci.getId()));
						item.add(new Label("lblName", ci.getText()));
				}
			};
		refreshArea.add(lv);				
		// 添加分页
		refreshArea.add(new Label("lblPageCount",new PropertyModel(pager,"msg")));
		refreshArea.add(new PagerAjaxLink("linkPageFirst","first"));
		refreshArea.add(new PagerAjaxLink("linkPagePrevious","previous"));
		refreshArea.add(new PagerAjaxLink("linkPageNext","next"));
		refreshArea.add(new PagerAjaxLink("linkPageEnd","last"));
	}
 
	private CheckItem getCheckedItem(List<CheckItem> items){
		for(CheckItem item : items){
			if (item.getChecked()){
				return item;
			}
		}
		
		return null;
	}
	
	public List<CheckItem> getItems(String tableName,Pager pager){
		String sql = "select id,name from " + tableName;
		
		Limits limit = Limits.none();
		if (pager == null){
			limit = Limits.none();
		}
		if(pager.getPageSize() <= 0){
			limit = Limits.none();
		}
				
		if(pager.getCurrentPage()==1){//第一页
			long totalRows = connection.count(sql); 
			pager.setTotalRows((int)totalRows);
			limit = Limits.of(pager.getStartRow(), pager.getPageSize());
		}

		//TODO:添加权限？
		List<CheckItem> list = connection.query(sql,  
				new RecordHandler<CheckItem>() { 
					public CheckItem mapping(ResultSet rs, SQLConnection connection) throws Exception {
						CheckItem ci = new CheckItem(rs.getString("id"),rs.getString("name"));
						return ci;
					}
			},limit);
		
		return list;
	}

	
	public void changeItems(String tableName) {
		this.tableName = tableName;
		this.items.clear();
		this.pager.first();
		this.items.addAll(getItems(tableName,pager));				
	}

	public void setItems(List<CheckItem> items) {
		this.items = items;
	}
	
	public List<CheckItem> getItems(){
		return items;
	}

	public CheckItem getCheckedItem() {
		return checkedItem;
	}
	private class PagerAjaxLink extends AjaxFallbackLink<Object>{
		
		private static final long serialVersionUID = 1L;
		private String op;
		public PagerAjaxLink(String id,String op) {
			super(id);
			this.op=op;
		}

		@Override
		public boolean isEnabled(){
			if (op.equalsIgnoreCase("first")){	
				return pager.getCurrentPage() != 1;
			}
			if (op.equalsIgnoreCase("previous")){	
				return pager.getCurrentPage() != 1;
			}
			if (op.equalsIgnoreCase("next")){	
				return (pager.getCurrentPage() != pager.getTotalPages()) &&(pager.getTotalPages() != 0 );
			}
			if (op.equalsIgnoreCase("last")){	
				return (pager.getCurrentPage() != pager.getTotalPages())&&(pager.getTotalPages() != 0 );
			}
			
			return true;
			
		}
		
		@Override
		public void onClick(AjaxRequestTarget target) {
			if (op.equalsIgnoreCase("first")){	
				pager.first();
			}
			if (op.equalsIgnoreCase("previous")){	
				pager.previous();
			}
			if (op.equalsIgnoreCase("next")){	
				pager.next();
			}
			if (op.equalsIgnoreCase("last")){	
				pager.last();
			}
			
			items.clear();
			items.addAll(getItems(tableName,pager));				
        	target.addComponent(refreshArea);
		}
					  
	  }
	 
}
